from aip import AipOcr
import time

# 识别图片文字,还是比较准确的，赞
APPP_ID = '18268607'
API_KEY = 'qwzaUW2z6NgjVNNlKYiXgPpX'
SECRET_KEY = 'Cs75lIXTx8WWGRuIWxf1ghnNYugQ3E0L'

client = AipOcr(APPP_ID, API_KEY, SECRET_KEY)


def delay():
    time.sleep(2)


def toText(imageBytes, text):

    delay()
    message = client.basicGeneral(imageBytes)
    # message = client.basicAccurate(imageBytes)

    print("message:" + str(message))
    if message is None:
        return None
    for msg in message.get('words_result'):
        word = msg.get('words')
        print(f"find :{text},from {word}")
        if word.startswith(text):
            return word

    return None


def toTextContains(imageBytes, text):
    delay()
    message = client.basicGeneral(imageBytes)

    print("message:" + str(message))
    if message is None or message is "":
        return None

    for msg in message.get('words_result'):
        word = msg.get('words')
        print(f"find :{text},from {word}")
        if word.find(text, 0, len(word)) > 0:
            return word

    return None


# 返回包含子串的列表
def toTextList(imageBytes, text=None):
    delay()
    message = client.basicGeneral(imageBytes)

    print("message:" + str(message))
    if message is None:
        return None
    list = []
    for msg in message.get('words_result'):
        word = msg.get('words')
        print(word)
        if text is None:
            list.append(word)
        else:
            if word.find(text, 0, len(word)):
                list.append(word)

    return list


# 返回包含子串的列表
def toTextListContains(imageBytes, text):
    delay()
    message = client.basicGeneral(imageBytes)

    print("message:" + str(message))
    if message is None:
        return None
    list = []
    for msg in message.get('words_result'):
        word = msg.get('words')
        print(f"find :{text},from {word}")
        if word.find(text, 0, len(word)) > 0:
            list.append(word)

    return list
